package com.village.friend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.village.friend.entity.AppUserMapping;
import com.village.friend.mapper.AppUserMappingMapper;
import com.village.friend.service.AppUserMappingService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yl
 * @since 2020-09-18
 */
@Service
public class AppUserMappingServiceImpl extends ServiceImpl<AppUserMappingMapper, AppUserMapping> implements AppUserMappingService {
    private static Log log = LogFactory.getLog(AppUserMappingService.class);
    /**
     * 查询用户下的团队
     * @param username
     * @return
     */
    @Override
    public List<AppUserMapping> findSubUsers(String username){
        List<AppUserMapping> list = null;
        try {
            QueryWrapper<AppUserMapping> qw = new QueryWrapper<>();
            qw.eq("parent_id",username);
            list = baseMapper.selectList(qw);
            list = delRepeat(list);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }


    /**
     * 查询所有上级
     * @param username
     */
    @Override
    public List<AppUserMapping> findParentUsers(String username){
        if(StringUtils.isEmpty(username))return null;
        AppUserMapping w = new AppUserMapping();
        w.setUserId(username);
        return queryMapping(w);
    }

    /**
     * 查找指定上级
     * @param username
     * @return
     */
    @Override
    public AppUserMapping findParentUser(String username, Integer level){
        QueryWrapper<AppUserMapping> qw = new QueryWrapper<>();
        qw.eq("user_id", username);
        qw.eq("lv", level);
        return baseMapper.selectOne(qw);
    }


    /**
     * 查詢記錄
     * @param bean
     * @return
     */
    private List<AppUserMapping> queryMapping(AppUserMapping bean){
        List<AppUserMapping> list = null;
        QueryWrapper<AppUserMapping> qw = genQueryWrapper(bean);
        try {
            list = baseMapper.selectList(qw);
        }  catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }


    /**
     * 插入用户关系
     * @param username
     * @param parantId
     */
    @Override
    @Transactional
    public void insertUserMapping(String username, String parantId){

        try {

            List<AppUserMapping> parentUsers = genInsertParents(username,parantId);
            if(parentUsers.size() > 0) {
                saveBatch(parentUsers);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除用户映射
     * @param username
     */
    @Override
    @Transactional
    public void deleteUser(String username){
        try {
            //查询上级
            AppUserMapping parent = findParentUser(username,1);

            //查询下级
            List<AppUserMapping> subUser = findSubUsers(username);

            //删除上级映射
            deleteParent(username);

            //下级用户,先删除上级 再重新添加被删除用户的上级
            if(subUser != null && subUser.size() > 0){
                List<AppUserMapping> insertMappings = new ArrayList<>();
                for (int i = 0; i < subUser.size(); i++) {
                    AppUserMapping userMapping = subUser.get(i);
                    //删除所有上级
                    deleteParent(userMapping.getUserId());
                    //添加到待插入列表
                    insertMappings.addAll(genInsertParents(userMapping.getUserId(), parent.getUserId()));
                }
                //统一插入
                if(!insertMappings.isEmpty()){
                    saveBatch(insertMappings);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 生成需要插入的上级映射
     * @param username
     * @param parantId
     * @return
     */
    private List<AppUserMapping> genInsertParents(String username, String parantId){
        List<AppUserMapping> parentUsers = new ArrayList<>();
        //当前映射关系
        if(StringUtils.isEmpty(parantId)){
            return parentUsers;
        }
        parentUsers.add(genMapping(username,parantId,1));

        //所有上级的映射关系
        List<AppUserMapping> list = findParentUsers(parantId);

        //插入上级
        if(list != null && !list.isEmpty()){
            log.info("需插入" + list.size() + "个上级");
            for (int i = 0; i < list.size(); i++) {
                AppUserMapping item = list.get(i);
                if(item.getLv() != null) {
                    parentUsers.add(genMapping(username,item.getParentId(),item.getLv() + 1));
                }
            }
        }
        return parentUsers;
    }


    // 去重
    public List<AppUserMapping> delRepeat(List<AppUserMapping> list) {
        if(list == null)return null;

        List<AppUserMapping> listNew = new ArrayList<>();

        for (int j = 0; j < list.size(); j++) {
            AppUserMapping mapping = list.get(j);

            if(listNew.isEmpty()){
                listNew.add(mapping);
            }else {
                boolean isAdd = true;
                for (int i = 0; i < listNew.size(); i++) {
                    if(mapping.getUserId().equals(listNew.get(i).getUserId())){
                        isAdd = false;
                        break;
                    }
                }
                if(isAdd){
                    listNew.add(mapping);
                }
            }
        }
        return listNew ;
    }



    /**
     * 查询几级之前的团队
     * @param username
     * @param startDate  0为当天0点 -1表示查询所有
     * @param maxLevel 最大的团队层级
     * @return
     */
    public List<AppUserMapping> findLessTeams(String username, int maxLevel, int startDate){
        QueryWrapper<AppUserMapping> qw = new QueryWrapper<>();
        qw.eq("parent_id", username);
        qw.lt("lv",maxLevel);

        List<AppUserMapping> list = new ArrayList<>();
        try {
            list = baseMapper.selectList(qw);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }


    /**
     * 删除上级记录
     * @param username
     * @return
     */
    private void deleteParent(String username){
        try {
            AppUserMapping w = new AppUserMapping();
            w.setUserId(username);
            QueryWrapper<AppUserMapping> queryWrapper = genQueryWrapper(w);
            baseMapper.delete(queryWrapper);
            log.info("删除用户映射关系:" + username);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 生成mapping
     * @param username
     * @param parantId
     * @param level
     * @return
     */
    private AppUserMapping genMapping(String username, String parantId, int level){
        AppUserMapping w = new AppUserMapping();
        w.setUserId(username);
        w.setParentId(parantId);
        w.setLv(level);
        return w;
    }

    /**
     * 生成查询条件
     * @param bean
     * @return
     */
    private QueryWrapper<AppUserMapping> genQueryWrapper(AppUserMapping bean){
        QueryWrapper<AppUserMapping> qw = new QueryWrapper<>();
        if(Strings.isNotBlank(bean.getUserId())){
            qw.eq("user_id", bean.getUserId());
        }
        if(Strings.isNotBlank(bean.getUserId())){
            qw.eq("parent_id", bean.getParentId());
        }
        if(bean.getLv() != null){
            qw.eq("lv", bean.getLv());
        }
        return qw;
    }

    /**
     * 该方法是用来生成映射关系的.目前执行过了,没用的
     */
    @Deprecated
    public void importUserMapping(){
        List<AppUserMapping> list = null;
        try {
            list = baseMapper.selectList(null);
            if(list != null && !list.isEmpty()){
                log.info("列表条数:" + list.size());
                for (int i = 0; i < list.size(); i++) {
                    next(list.get(i),list);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void next(AppUserMapping bean,List<AppUserMapping> list) {
        //上级id没有就返回
        if(bean.getParentId() == null || "-1".equals(bean.getParentId()))return;

        //从列表中取出上级用户
        AppUserMapping appUserMapping = null;
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).getUserId().equals(bean.getParentId())){
                appUserMapping = list.get(i);
                break;
            }
        }
        //没有上级用户 就返回
        if(appUserMapping == null) return;

        //取到后 把层级+1 并存储映射关系
        AppUserMapping ins = insert(bean.getUserId(),appUserMapping.getParentId(), bean.getLv() + 1);
        next(ins,list);

    }

    /**
     * 插入一条数据
     * @param username
     * @param parantId
     * @param level
     * @return
     */
    private AppUserMapping insert(String username, String parantId, int level){
        AppUserMapping w = genMapping(username,parantId,level);
        try {
            baseMapper.insert(w);
            log.info("插入用户关系映射: username = " + ", parentId = " + w.getParentId() + " , level = " + w.getLv() );
        } catch (Exception e) {
            e.printStackTrace();
        }

        return w;
    }




}
